import sendfile from 'koa-sendfile';
import uuid from 'uuid';
import convert from 'koa-convert';
import body from 'koa-better-body';
import fs from 'fs';
import { Book, Secret, User } from '../models';
import { checkUserToken, checkAdminToken } from '../utils/jwt';
import uploadToTencentCos from '../utils/txCosUpload';
import { mongosync } from '../bin/mongosync';

export default function (router) {
  router.get('/api/get_text', async ctx => {
    const arr = ['读万卷书,行万里路。 ——顾炎武', '读过一本好书，像交了一个益友。 ——臧克家', '鸟欲高飞先振翅，人求上进先读书', '书籍是人类思想的宝库', '书山有路勤为径，学海无涯苦作舟'];
    const date = new Date();
    const day = date.getDate() % 5;
    ctx.body = { ok: true, text: arr[day] };
  });

  // 下载上传模板文件
  router.get('/api/download', async ctx => {
    const path = decodeURIComponent(ctx.request.query.path);
    ctx.attachment(decodeURI(path));
    await sendfile(ctx, path);
  });

  router.get('/help', async ctx => {
    await ctx.render('help', {
      title: '帮助与反馈'
    });
  });

  router.get('/notice', async ctx => {
    await ctx.render('notice', {
      title: '关注公众号'
    });
  });

  /**
   * 获取个人阅读时长
   */
  router.get('/api/read_time/my', async (ctx, next) => {
    let userid = await checkUserToken(ctx, next);
    if (userid) {
      const readTime = (await User.findById(userid, 'read_time')).read_time;
      const minute = parseInt(readTime / (1000 * 60));
      // 可兑换个书币数
      const num = parseInt(minute * (10 / 60));
      ctx.body = { ok: true, minute, num, msg: '获取我的阅读时长成功' };
    }
  });

  /**
   * 兑换书币
   */
  router.get('/api/read_time/exchange', async (ctx, next) => {
    let userid = await checkUserToken(ctx, next);
    if (userid) {
      const readTime = (await User.findById(userid, 'read_time')).read_time;
      const minute = parseInt(readTime / (1000 * 60));
      // 可兑换个书币数
      const num = parseInt(minute * (10 / 60));
      const awardResult = await User.addAmount(userid, num, '阅读时长兑换奖励');
      if (awardResult) {
        const updateResult = await User.updateOne({ _id: userid }, { $set: { read_time: 0 } });
        if (updateResult.ok === 1 && updateResult.nModified === 1) {
          ctx.body = { ok: true, msg: '兑换书币成功' };
        } else {
          await User.reduceAmount(userid, num);
          ctx.body = { ok: false, msg: '兑换书币失败' };
        }
      } else {
        ctx.body = { ok: false, msg: '发送书币失败' };
      }
      ctx.body = { ok: true, minute, num, msg: '获取我的阅读时长成功' };
    }
  });

  /**
   * 手动同步mongo数据库
   */
  router.get('/api/mongosync', async (ctx, next) => {
    let userid = await checkAdminToken(ctx, next, 'mongosync');
    if (userid) {
      let result = await mongosync();
      if (result === true) {
        ctx.body = { ok: true, msg: '同步成功' };
      } else {
        ctx.body = { ok: false, msg: '同步失败' };
      }
    }
  });

  /**
   * 后台上传图片
   */
  router.post('/api/admin/upload-img', convert(body()), async ctx => {
    const file = ctx.request.files[0]; // 获取上传文件
    const buffer = fs.readFileSync(file.path);
    const ext = file.name.split('.').pop(); // 获取上传文件扩展名
    const name = uuid.v1();
    const key = `mbook/${name}.${ext}`;
    try {
      const url = await uploadToTencentCos({
        Bucket: 'picture',
        Body: buffer,
        Type: 'buffer',
        Key: key,
        useCdn: true
      });
      await ctx.json(true, '上传图片成功', { name, url });
    } catch (err) {
      await ctx.json(false, `上传图片失败, ${err.toString()}`);
    }
  });

  /**
   * 前端上传图片
   */
  router.post('/api/front/upload-img', convert(body()), async ctx => {
    const file = ctx.request.files[0]; // 获取上传文件
    const buffer = fs.readFileSync(file.path);
    const ext = file.name.split('.').pop(); // 获取上传文件扩展名
    const name = uuid.v1();
    const key = `mbook/fe/${name}.${ext}`;
    try {
      const url = await uploadToTencentCos({
        Bucket: 'picture',
        Body: buffer,
        Type: 'buffer',
        Key: key,
        useCdn: true
      });
      await ctx.json(true, '上传图片成功', { name, url });
    } catch (err) {
      await ctx.json(false, `上传图片失败, ${err.toString()}`);
    }
  });

  /**
   * 渲染引导打开小程序的页面
   */
  router.get('/api/render_open_weixin', async ctx => {
    const { secret } = ctx.request.query;
    const thisSecret = await Secret.findOne({ _id: secret });
    if (!thisSecret) {
      // 渲染错误页面
      return;
    }
    const thisBook = await Book.findOne({ _id: thisSecret.bookid }, 'name author img des');
    if (!thisBook) {
      // 渲染错误页面
      return;
    }
    await ctx.render('guide-unlock', {
      link: `/pages/bookdetail/index?id=${thisBook._id}&pre_secret=${thisSecret._id}`,
      name: thisBook.name,
      author: thisBook.author,
      img: thisBook.img_url || 'https://picture-1256514897.file.myqcloud.com/book/codes/default-book-img.png',
      des: thisBook.des
    });
  });
}
